<!DOCTYPE html>
<body>
<head>
    <meta charset="utf-8">
    <#include "/pubHeadStyleTree.html">
</head>
<body>
<link type="text/css" rel="stylesheet" href="${ctx}/display/displaymodel.css" />
<link type="text/css" rel="stylesheet" href="${ctx}/display/jquery.qtip.min.css" />
<link type="text/css" rel="stylesheet" href="${ctx}/workflowStatic/style/css/definition.node.css" />
<script src="${ctx}/display/jquery.qtip.min.js"></script>
<script src="${ctx}/display/raphael.js"></script>
<script src="${ctx}/workflowStatic/js/displaymodel.js"></script>
<script src="${ctx}/workflowStatic/js/bpmn-draw.js"></script>
<script src="${ctx}/workflowStatic/js/bpmn-icons.js"></script>
<script src="${ctx}/workflowStatic/js/Polyline.js"></script>
<div style="border: blue solid 1px; margin: 10px; border-radius: 10px; overflow: auto; position: absolute; top: 0; bottom:0; left:0; right:0;">
    <form class="layui-form">
        <div id="bpmnModel" style="margin-bottom: 100px;margin-left: 10px;font-size: 8px;color: blue"></div>
        <div id="userRecords" style="margin-bottom: 20px;margin-left: 10px;font-size: 14px;color: blue"></div>
        <div style="color: red; margin: 10px">历史修改记录，若选择后则只能使用历史人员</div>
        <#list allHistory as item>
            <div>
                <input type="radio" class="choose_history" lay-filter="choose_history" name="history" value="${item.id}">
                <input value='${item.historyStr}' class="historyStr" style="display: none">
                <#list item.history as history>
                    ${history.nodeName}:${history.userName}&nbsp;
                </#list>
                <a class="layui-icon layui-icon-close-fill deleteHistory" delId="${item.id}"></a>
            </div>
        </#list>
    </form>
<div style="text-align: center;margin: 10px auto;width:100%;">
    <button class="layui-btn save" onclick="selectUser()">确认</button>
    <button class="layui-btn cancelFrom layui-btn-danger" onclick="cancle()">取消</button>
</div>
</div>

<script type="text/javascript">
    layui.config({
        base: serverPath.systemPath + staticPath.systemPath //静态资源所在路径
    }).extend({
        index: 'index' //主入口模块
    }).use(['index','element', 'table', 'setter', 'util', 'form','layer','jquery', 'commons'], function () {
        var element = layui.element,
            table=layui.table,
            form = layui.form,
            $ = layui.jquery,
            commons = layui.commons,
            layer = layui.layer;

        element.render();
        form.render();
        table.render();


        var modelId = "${actDefModel.id!}";
        var procDefId = "${actDefModel.procDefId!}";
        var setter=layui.setter;
        var selUserNode = [];//保存节点执行人信息
        var dataPrivacyLevel = "${dataPrivacyLevel}";

        showDiagram(modelId);

        function showDiagram(modelId) {
            var modelUrl = '${ctx}/workflow/bpmnImage/json/getByModelId';
            $.ajax({
                url: modelUrl + '?nocaching=' + new Date().getTime()+'&modelId='+modelId,
                type: "get",
                contentType: 'application/json',
                dataType: 'json',
                success: function (data) {
                    if ((!data.elements || data.elements.length == 0) && (!data.pools || data.pools.length == 0)) return;

                    INITIAL_CANVAS_WIDTH = data.diagramWidth;
                    INITIAL_CANVAS_WIDTH += 30;

                    INITIAL_CANVAS_HEIGHT = data.diagramHeight;
                    canvasWidth = INITIAL_CANVAS_WIDTH;
                    canvasHeight = INITIAL_CANVAS_HEIGHT;
                    viewBoxWidth = INITIAL_CANVAS_WIDTH;
                    viewBoxHeight = INITIAL_CANVAS_HEIGHT;

                    $('#bpmnModel').width(INITIAL_CANVAS_WIDTH);
                    $('#bpmnModel').height(INITIAL_CANVAS_HEIGHT);
                    <!--创建画布-->
                    paper = Raphael(document.getElementById('bpmnModel'), canvasWidth, canvasHeight);
                    paper.setViewBox(0, 0, viewBoxWidth, viewBoxHeight, false);
                    paper.renderfix();

                    if (data.pools)
                    {
                        for (var i = 0; i < data.pools.length; i++)
                        {
                            var pool = data.pools[i];
                            _drawPool(pool);
                        }
                    }

                    var modelElements = data.elements;
                    for (var i = 0; i < modelElements.length; i++)
                    {
                        var element = modelElements[i];
                        var drawFunction = eval("_draw" + element.type);
                        drawFunction(element);
                        _showTip($("#"+element.id),element);

                    }

                    if (data.flows)
                    {
                        for (var i = 0; i < data.flows.length; i++)
                        {
                            var flow = data.flows[i];
                            if (flow.type === 'sequenceFlow') {
                                _drawFlow(flow);
                            } else if (flow.type === 'association') {
                                _drawAssociation(flow);
                            }
                        }
                    }
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    layer.alert("暂无数据，请稍后操作！" + XMLHttpRequest.status);
                }
            });
        }

        function _showTip(htmlNode, element)
        {
            var type=element.type,
                id=element.id;
            var items= getItems(id,type);
            if(!items)return;
            if(items.length==0)return;
            var item,html=['<div class="edui-menu-body">'];
            while(item=items.pop()){
                if(item.id=='-'){
                    html.push('<div class="edui-menuitem edui-menuseparator"><div class="edui-menuseparator-inner"></div></div>');
                }
                else{
                    html.push("<div class=\"edui-menuitem edui-for-"+item.id+"\" onmouseover=\"$(this).addClass('edui-state-hover')\" onmouseout=\"$(this).removeClass('edui-state-hover')\" onclick=\"clickHandler(this.id,'"+element.type+"','"+element.id+"','"+element.name+"')\" id=\""+item.id+"\"><div class=\"edui-box edui-icon\"></div><div class=\"edui-box edui-label edui-menuitem-label\">"+item.text+"</div></div>");
                }
            }
            html.push('</div>');

            var text = element.type + " ";
            if (element.name && element.name.length > 0)
            {
                text += element.name;
            }
            else
            {
                text += element.id;
            }

            htmlNode.qtip({
                content: {
                    text: html.join(''),
                    title: {
                        text: text
                    }
                },
                position: {
                    my: 'top left',
                    at: 'bottom center',
                    viewport: jQuery('#bpmnModel')
                },
                hide: {
                    event:'click mouseleave',
                    leave: false,
                    fixed:true,
                    delay:300
                },
                style: {
                    classes: 'ui-tooltip-kisbpm-bpmn'
                }
            });
        }

        function getItems(id,type) {
            var items = [];
            if(type == 'UserTask'){
                items = [
                    {id:'selectUser',text:'选择人员'}
                ];
            }
            return items;
        }
        clickHandler =  function(itemId,type,id,name) {
            if (name === "null") {
                name = "";
            }
            var body;
            var userSelectorWin;
            parent.layer.open({
                type: 2,
                title: '人员选择器',
                shade: 0.3,
                area: ['760px','630px'],
                btn:["保存","取消","撤销"],
                resize:false,
                content:serverPath.systemPath + setter.sysLinkPath+ "dialog/view/singleSysUserDialog?dataPrivacyLevel=" + dataPrivacyLevel,  // todo 添加密级字段
                success: function(layero, index){
                    body = parent.layer.getChildFrame('body', index);
                    userSelectorWin = parent.window[layero.find('iframe')[0]['name']];
                },
                yes: function(index, layero){
                    // 执行iframe页的save方法
                    userSelectorWin.saveData(index);
                    var theUserList = body.find("input[name=selectUser]").val();
                    if(theUserList!=="\"\""){
                        var item = JSON.parse(theUserList);
                        var userId = item.userId;
                        var userName = item.fullName;
                        var json = {"nodeId":id,"nodeName":name,"userId":userId,"userName":userName};
                        var tmpNodeArr = [];
                        for(var i=0; i<selUserNode.length; i++){
                            var node = selUserNode[i];
                            if (node.nodeId != id) {
                                tmpNodeArr.push(node);
                            }
                        }
                        tmpNodeArr.push(json);
                        selUserNode = tmpNodeArr;
                        var obj = $("#userRecords").children();
                        if(obj.length == 0){
                            $("#userRecords").append("<div style='font-size: 16px;font-family: \"Microsoft YaHei\";' id='node_" + id + "'>"+"节点:"+ name +",人员："+ userName +"</div>");
                        }else{
                            for(var i = 0; i<obj.length; i++){
                                var itemId = $(obj[i]).attr("id");
                                if(itemId == ("node_"+ id)){
                                    $("#node_"+id).html("节点:"+ name +",人员："+ userName);
                                    parent.layer.close(index);
                                    return;
                                }
                            }
                            $("#userRecords").append("<div style='font-size: 16px;font-family: \"Microsoft YaHei\";' id='node_" + id + "'>"+"节点:"+ name +",人员："+ userName +"</div>");
                        }
                        parent.layer.close(index);
                    }else {
                        parent.layer.close(index);
                    }
                },
                btn3:function (index, layero) {
                    userSelectorWin.cancelData(index);
                    // 开启该代码可机制点击该按钮关闭
                    return false;
                }
            })
        };
        selectUser = function(){
            if (selUserNode.length > 0) {
                // 先把值传到父页面去
                var userHistory = JSON.stringify(selUserNode);
                parent.callback(userHistory);
                var radioCheck = $("input[name='history']:checked");
                if(radioCheck.length<1){
                    $.ajax({
                        type: "post",
                        dataType:"json",
                        url : serverPath.workflowPath + setter.workflowLinkPath +'bpmFlowUserHistory/add',
                        data:{procDefId: procDefId, userHistory:userHistory},
                        success:function (result) {
                            if (commons._filterRecord(result)) {
                                parent.layer.close(parent.layer.getFrameIndex(window.name));
                            } else {
                                window.parent.layer.alert(result.msg);
                            }
                        }
                    })
                }else{
                    parent.layer.close(parent.layer.getFrameIndex(window.name));
                }
            }else{
                parent.layer.closeAll();
            }

            
        };
        cancle = function () {
            var index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
        }


        $(".deleteHistory").click(function () {
            var that = $(this);
            var id = that.attr("delId");
            layer.confirm("确定要删除此配置信息吗？", function (index) {
                layer.close(index);
                $.ajax({
                    type:"post",
                    dataType:"json",
                    url: serverPath.workflowPath + setter.workflowLinkPath +"bpmFlowUserHistory/deleteById",
                    data: {id: id},
                    success: function (result) {
                        if (commons._filterRecord(result)) {
                            that.parent().remove();
                        }
                    }
                });

            });

        });

        form.on('radio(choose_history)', function (obj) {
            var historyStr = $(obj.elem).parent().find(".historyStr").val();
            selUserNode = eval(historyStr);
        });
    });
</script>
</body>
</html>

